package com.ecar.apm.util;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.URLEncoder;

/**
 * @Author meyer@HongYe
 */
@Component
public class SendSMSUtil {

    public static String sendMessage(String mobile,String message) throws Exception {

        String url = "http://api.qirui.com:7891/mt";
        //apiKey和APISecret
        String apiKey = "1766620013";
        String apiSecret = "7d748a17f9fa57f3df8c";

        StringBuilder sb = new StringBuilder(2000);
        sb.append(url);
        sb.append("?dc=15");
        sb.append("&sm=").append(URLEncoder.encode(message, "utf8"));
        sb.append("&da=").append(mobile);
        sb.append("&un=").append(apiKey);
        sb.append("&pw=").append(apiSecret);
        sb.append("&tf=3&rd=1&rf=2");   //短信内容编码为 urlencode+utf8

        String request = sb.toString();

        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(request);
        CloseableHttpResponse response = client.execute(httpGet);

        String respStr = null;
        HttpEntity entity = response.getEntity();
        if(entity != null) {
            respStr = EntityUtils.toString(entity, "UTF-8");
        }
        return respStr;
    }

    private static String message;
    @Value("${sms.templateMessage}")
    public void setMessage(String templateMessage) {
        SendSMSUtil.message = templateMessage;
    }
    public static void main(String[] args) {
        System.out.println("mobiles = " + message);
    }
}
